﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using ZOIL.Framework.Core;
using ZOIL.Framework.Presentation;

namespace ZOIL.Library.Devices
{
    public class KeyboardInputBehavior : ZInputBehavior<ZInformationLandscape>
    {
        #region method overrides

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.KeyDown += OnKeyDown;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.KeyDown -= OnKeyDown;

            base.OnDetaching();
        }

        protected override void OnIsZoomingEnabledChanged(bool oldIsZoomingEnabled, bool newIsZoomingEnabled)
        {
            base.OnIsZoomingEnabledChanged(oldIsZoomingEnabled, newIsZoomingEnabled);

            if (AssociatedObject == null) return;

            if (IsZoomingEnabled)
                AssociatedObject.KeyDown += OnKeyDown;
            else
                AssociatedObject.KeyDown -= OnKeyDown;
        }

        #endregion

        #region event handling

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            // Keyboard events are only processed for this.Landscape, if ...
            // 1. mouse pointer is inside the landscape
            // 2. and the landscape is the "deepest" one at this mouse position down the visual tree
            if (!AssociatedObject.IsMouseOver || (ZTreeHelper.TryFindParent<ZInformationLandscape>((DependencyObject)Mouse.DirectlyOver) != AssociatedObject))
                return;

            switch (e.Key)
            {
                // Key down means zoom out
                case Key.Down:
                    {
                        // Zoom out of landscape (with zooming ref point at mouse position)
                        AssociatedObject.ZoomBy(Mouse.GetPosition(AssociatedObject), 0.7, true);
                        break;
                    }

                // Key up means zoom in
                case Key.Up:
                    {
                        // Zoom into landscape (with zooming ref point at mouse position)
                        AssociatedObject.ZoomBy(Mouse.GetPosition(AssociatedObject), 1.0 / 0.7, true);
                        break;
                    }
            }
        }

        #endregion
    }
}
